package com.example.emos.wx.controller;

import com.example.emos.wx.common.util.R;
import com.example.emos.wx.config.shiro.JwtUtil;
import com.example.emos.wx.controller.form.LoginForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.emos.wx.controller.form.RegisterForm;
import com.example.emos.wx.service.UserService;
import javax.validation.Valid;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api("用户模块Web接口")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtUtil jwtUtil;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Value("${emos.jwt.cache-expire}")
	private int cacheExpire;

	/**
	 * 注册用户
	 * @param form
	 * @return
	 */
	@PostMapping("/register")
	@ApiOperation("注册用户")
	public R register(@Valid @RequestBody RegisterForm form){
		int id=userService.registerUser(form.getRegisterCode(),form.getCode(),form.getNickname(),form.getPhoto());
		String token=jwtUtil.createToken(id);
		Set<String> permsSet=userService.searchUserPermissions(id);
		saveCacheToken(token,id);
		return R.ok("用户注册成功").put("token",token).put("permission",permsSet);
	}


	/**
	 * 用户登录
	 * @param form
	 * @return
	 */
	@PostMapping("/login")
	@ApiOperation("登陆系统")
	public R login(@Valid @RequestBody LoginForm form){
		int id=userService.login(form.getCode());
		String token=jwtUtil.createToken(id);
		saveCacheToken(token,id);
		Set<String> permsSet = userService.searchUserPermissions(id);
		return R.ok("登陆成功").put("token",token).put("permission",permsSet);
	}



	/**
	 * 把token缓存到redis
	 * @param token
	 * @param userId
	 */
	private void saveCacheToken(String token,int userId){
		redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);
	}

}
